import { pendingRequests, getRequestIdentifier } from './index';

const handleResponse = response => {
  // 1. 移除请求标识
  const requestId = getRequestIdentifier(response.config);
  pendingRequests.delete(requestId);

  // 2. 统一响应处理
  const res = response.data;
  if (res.code !== 0) {
    // 业务错误处理
    const error = new Error(res.message || '请求失败');
    error.code = res.code;
    return Promise.reject(error);
  }

  return res.data;
}


const responseInterceptor = {
  onFulfilled(response) {
    handleResponse(response);
    return response;
  },
  onRejected(error) {
    return Promise.reject(error);
  }
}

export default responseInterceptor;
